package com.wukang.photovoltaicinspectionpictures.base

import androidx.lifecycle.ViewModel
import com.wukang.photovoltaicinspectionpictures.logger.Rog
import java.lang.ref.WeakReference

/**
 * 基础[ViewModel]
 * @author wukang
 */
abstract class BaseViewModel : ViewModel() {
    private var activityRef: WeakReference<BaseActivity<*, *>>? = null

    internal fun setActivity(activity: BaseActivity<*, *>) {
        activityRef = WeakReference(activity)
    }

    protected fun useActivity(block: BaseActivity<*, *>.() -> Unit) {
        activityRef?.get()?.also {
            it.block()
        } ?: Rog.e("BaseViewModel", "${this::class.java.simpleName} activityRef or Activity is null")
    }

    override fun onCleared() {
        super.onCleared()
        activityRef?.clear()
        activityRef = null
    }
}